package PSNRCounter;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;

import XmlLoader.FGObjProcess;
import XmlLoader.FGObjectTrajectoryStructure;

public class PSNRCount
{
   public static double countPSNR(String file1, String file2) {
	   double psnr = 0.0;
	   double mse = 0.0;
	   //load image
	   try {
		   BufferedImage img1 = ImageIO.read(new File(file1));
		   BufferedImage img2 = ImageIO.read(new File(file2));
		   int width = img1.getWidth();
		   int height = img1.getHeight();
			Raster r1 = img1.getRaster();
			Raster r2 = img2.getRaster();
			for (int j = 0; j < height; j++)
				for (int i = 0; i < width; i++)
					mse += Math.pow(r1.getSample(i, j, 0) - r2.getSample(i, j, 0), 2);
			mse /= (double) (width * height);
			int maxVal = 255;
			double x = Math.pow(maxVal, 2) / mse;
			psnr = 10.0 * logbase10(x);
	   } 
	   catch (IOException e) {
		// TODO Auto-generated catch block
		   e.printStackTrace();
	   }
	   
	   return psnr;
   }
   
   public static double logbase10(double x) {
		return Math.log(x) / Math.log(10);
   }
   
   public static void main( String[] args ) {
	   String filePath_orgVideoFrameList = "D:/research/Proj1 cross road/data2/20130312_video_cross_road_cut/orgResult";
	   String filePath_combinedFrameList = "D:/research/Proj1 cross road/data2/20130312_video_cross_road_cut/result";
	   
	   String fileNameOrgImg = null;
	   String fileNameCombinedImg = null;
	   
	   double avgPsnr = 0.0;
	   int maxImgNum = 70193;
	   
	   File file = new File("D:/research/Proj1 cross road/data2/20130312_video_cross_road_cut/r.csv");
	   try
	   {
	       FileWriter fwriter = new FileWriter(file);
	   	   //Load each result image and count PSNR
	   	   int indexOrgImg = 0, indexCombinedImg = 0;
	   	   while(indexOrgImg < maxImgNum) {
	   		   fileNameOrgImg = filePath_orgVideoFrameList + "/" + indexOrgImg + ".jpg";
	   		   fileNameCombinedImg = filePath_combinedFrameList + "/" + FGObjProcess.ACT005_numFormat(Integer.toString(indexCombinedImg)) + ".jpg";
	   		   double getPsnr = PSNRCount.countPSNR(fileNameOrgImg, fileNameCombinedImg);
	   		   System.err.println("Org=" + indexOrgImg + " Comb=" + indexCombinedImg + " PSNR=" + getPsnr);
	   		   fwriter.append(getPsnr + "\n");
	   		   
	   		   indexOrgImg = indexOrgImg + 1;
	   		   indexCombinedImg = indexCombinedImg + 1;
	   	   }
	   	   fwriter.append("\nAverage Psnr = " + avgPsnr + "\n");
	   	   fwriter.close();
	    }
	    catch(Exception e)
	    {
	      e.printStackTrace();
	    }
   }
}